from datetime import datetime

from django.db.models import Sum
from django.http import JsonResponse
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.user.cxcuserserializer import UserSerializer, BudgetSerializer
from common.response_code import RET, error_map

from db.models import XlzUser, XlzDisburse, XlzBudget
from libs.userinfo import userinfo


# 个人首页
class MyInfoViews(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = UserSerializer

    def get(self, request):
        try:
            uid = request.user.id
            # 获取数据
            user_que = self.queryset.filter(id=uid)
            # 调用封装好的函数
            clock, sum_day, sum_account = userinfo(user_que, uid)
            # 序列化
            user_info = self.get_serializer(user_que, many=True)
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': {
                    'head': user_info.data,
                    'clock_day': clock,
                    'sum_day': sum_day.days,
                    'sum_account': sum_account,
                },
            })
        except Exception as e:
            print(e)
            return AuthenticationFailed({"code": RET.UNKOWNERR, "msg": error_map[RET.UNKOWNERR]})


# 预算
class BudgetViews(GenericAPIView):
    queryset = XlzBudget.objects.all()
    serializer_class = BudgetSerializer

    # 显示预算
    def get(self, request):
        new_time = datetime.now()
        uid = request.user.id

        # 获取当前时间的月份数据
        budget_que = self.queryset.filter(user_id=uid, create_time__year=new_time.year,
                                          create_time__month=new_time.month)
        # 当月支出
        disburse_que = XlzDisburse.objects.filter(user_id=uid, keepaccounts_time__year=new_time.year,
                                                  keepaccounts_time__month=new_time.month)
        disburse_sum = disburse_que.aggregate(Sum("money"))['money__sum'] if disburse_que else 0
        if len(budget_que) == 1:
            # 序列化
            budget_data = self.get_serializer(budget_que, many=True)

            return Response({
                'code': 200,
                'msg': '请求成功',
                'month': new_time.month,
                'data':  budget_data.data,
            })
        elif len(budget_que) == 0:
            return Response({
                'code': 200,
                'msg': '请求成功',
                'month': new_time.month,
                'data': [{
                    "budget": 0,
                    "disburse": disburse_sum
                    }],
            })
        else:
            raise AuthenticationFailed({"code": RET.UNKOWNERR, "msg": error_map[RET.UNKOWNERR]})

    # 设置预算
    def post(self, request):
        new_time = datetime.now()
        uid = request.user.id
        budget = request.POST.get('budget')
        try:
            if float(budget) > 0:
                # 判断当前月份预算是否存在
                budget_que = self.queryset.filter(user_id=uid, create_time__year=new_time.year,
                                                  create_time__month=new_time.month)
                # 当月支出
                disburse_que = XlzDisburse.objects.filter(user_id=uid, keepaccounts_time__year=new_time.year,
                                                          keepaccounts_time__month=new_time.month)
                disburse_sum = disburse_que.aggregate(Sum("money"))['money__sum'] if disburse_que else 0
                if len(budget_que) == 1:
                    budget_que.update(budget=budget, disburse=disburse_sum)
                    return Response({
                        'code': 200,
                        'msg': '修改预算成功',
                    })
                elif len(budget_que) == 0:
                    XlzBudget.objects.create(user_id=uid, budget=budget, disburse=disburse_sum)
                    return Response({
                        'code': 200,
                        'msg': '添加预算成功',
                    })
                else:
                    raise AuthenticationFailed({"code": RET.UNKOWNERR, "msg": error_map[RET.UNKOWNERR]})

        except Exception as e:
            print(e)
            return JsonResponse({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


